package admin

import (
	"github.com/labstack/echo"
	"github.com/sirupsen/logrus"
	"net/http"
	"src/config"
	"src/model"
	"src/util/context"
	"src/util/log"
)

var adminforumpostLogger = log.GetLogger()

func writeadminforumpostLoggerLoggerLog(funcName, errMsg string, err error) {
	adminforumpostLogger.WithFields(logrus.Fields{
		"package":  config.LogMessage + "/admin",
		"file":     "forumpost.go",
		"function": funcName,
		"err":      err,
	}).Warn(errMsg)
}

func DeleteForumpost(c echo.Context) error {
	post := model.ForumPost{}
	err := c.Bind(&post)
	if err != nil {
		writeadminforumpostLoggerLoggerLog("DeleteForumpost", "1", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMsgParamWrong)
	}

	id := context.GetJWTUsername(c)
	_, err = model.FindAdmin(id)
	if err != nil {
		writeadminforumpostLoggerLoggerLog("DeleteForumpost", "2", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.Hasnotpower)
	}

	err = model.DeleteForumPost(string(post.ID), post.UserID, true)
	if err != nil {
		writeadminforumpostLoggerLoggerLog("DeleteForumpost", "3", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorForumpostDelete)
	}

	var reply []model.Reply
	reply, err = model.GetReplyByPostALL(post.ID.Hex())
	if err != nil {
		writeadminforumpostLoggerLoggerLog("DeleteForumpost", "4", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorReplyGet)
	}
	for i := 0; i < len(reply); i++ {
		_, _ = model.DeleteReply(reply[i].ID.Hex(), reply[i].UserID, true)
	}

	var comment []model.Comment
	comment, err = model.GetCommentByForumpostALL(post.ID.Hex())
	if err != nil {
		writeadminforumpostLoggerLoggerLog("DeleteForumpost", "5", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorCommentGet)
	}
	for i := 0; i < len(comment); i++ {
		_, _ = model.DeleteComment(comment[i].ID.Hex(), comment[i].UserID, true)
	}

	return context.RetData(c, "")
}
